<template>
  <div class="room-detail-container">
    <div class="page-content-wrap" v-if="loaded">
      <div class="user-title" style="font-size: 26px;line-height: 2">{{ type.name }}</div>


      <div class="content-wrap">
        <div class="left-date">
          <div style="text-align: right;font-size: 14px;color: #aaa">只能预定30天之内</div>
          <el-config-provider :locale="locale">
            <el-calendar :range="dateRange">
              <template #date-cell="{ data }">
                <div style="width: 100%;height: 100%"
                     @click="onClickDay(data.day)" :class="{'un-in-range':!checkRange(data.day)}">
                  {{ data.day.split('-').slice(1).join('-') }}
                  {{ checkDaySelect(data.day) ? '✔️' : '' }}
                </div>
              </template>
            </el-calendar>
          </el-config-provider>
        </div>
        <div class="right-wrap">
          <div class="info">
            <div class="img-wrap">
              <img v-if="type.photo"
                   :src="uploadServer +  '/upload/image/' +type.photo"
              />
            </div>

          </div>
          <div class="price-wrap">
            <div class="line">
              单价：{{ type.price }} 元
            </div>
            <div class="line">
              选择天数：{{ dates.length }}
            </div>
            <div class="line">
              总价：<span style="font-weight: bold;font-size: 26px">{{ total }} 元</span>
            </div>
            <div class="pay-btn" @click="onClickPay">
              立即支付
            </div>
          </div>

        </div>
      </div>
    </div>

    <el-dialog v-model="showPayDialog" title="支付" width="330px" :show-close="false">
      <div style="width: 100%;height: 220px" v-loading="payLoading">

      </div>
      <div style="text-align: center">正在模拟支付...</div>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import $api from '@/api'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import {ElMessage, ElNotification, ElMessageBox} from "element-plus";

const uploadServer = import.meta.env.VITE_SERVER

const locale = zhCn

const id = ref(0)
const route = useRoute()
const router = useRouter()
const type = reactive({
  name: '',
  price: 0,
  photo: ''
})
const loaded = ref(false)
// 获取一个月后的日期
var currentDate = (new Date())
currentDate.setHours(0, 0, 0, 0);
var oneMonthLater = (new Date())
oneMonthLater.setHours(0, 0, 0, 0);
oneMonthLater.setDate(currentDate.getDate() + 30);
const dateRange = ref([currentDate, oneMonthLater])
onMounted(() => {
  var _id = route.params.id
  id.value = _id
  getDetail()
})
/**
 * 获取详情
 */
const getDetail = () => {
  loaded.value = false
  $api.webApi.getRoomsDetail(id.value).then(res => {
    type.name = res.name
    type.price = res.price
    type.photo = res.photo
    loaded.value = true
  }).catch(err => {
    if (err.data.code === 404) {
      router.push('/rooms')
    }
  })
}
/**
 * 日期选择
 */
const dates = ref([])

const onClickDay = (day) => {
  if (!checkRange(day)) {
    return
  }
  var index = dates.value.indexOf(day)
  if (index !== -1) {
    dates.value.splice(index, 1)
  } else {
    dates.value.push(day)
    dates.value = dates.value.sort(function (a, b) {
      const dateA = new Date(a);
      const dateB = new Date(b);
      return dateA.getTime() - dateB.getTime();
    })
  }
  refreshTotal()
}
/**
 * 费用计算
 */
const total = ref(0)
const checkDaySelect = (day) => {
  return dates.value.indexOf(day) !== -1
}
const refreshTotal = () => {
  total.value = dates.value.length * type.price
}
/**
 * 点击支付
 */
const showPayDialog = ref(false)
const payLoading = ref(true)
var loading = false
const onClickPay = () => {
  if (total.value <= 0) {
    ElMessage({
      message: '请选择入住日期',
      type: 'warning',
    })
  } else {
    if (loading) {
      return
    }
    loading = true
    showPayDialog.value = true
    setTimeout(() => {
      submitPay()
      showPayDialog.value = false
    }, 1500)

  }
}
const submitPay = () => {
  $api.webApi.createOrder({
    reserveDate: JSON.stringify(dates.value),
    typeId: id.value,
    unitPrice: type.price,
    price: total.value,
    days: dates.value.length
  }).then(res => {
    loading = false
    ElMessageBox.confirm(
        '预定信息已提交，请等待工作人员确认',
        '提示',
        {
          confirmButtonText: '确定',
          type: 'success',
          showCancelButton: false
        }
    )
        .then(() => {
          router.push('/user')
        })
        .catch(() => {
          router.push('/user')
        })
  }).catch(() => {
    loading = false
  })
}
/**
 * 检查日历日期是否在范围内
 */
const checkRange = (day) => {
  var start = dateRange.value[0]
  var end = dateRange.value[1]
  var d = new Date(day)
  return d <= end && d >= start
}
</script>

<style scoped lang="scss">
.room-detail-container {
  width: 100%;
  min-height: 900px;
  background-color: #fff;
}

.content-wrap {
  width: 100%;
  display: flex;

  > .left-date {
    width: 50%;
  }

  > .right-wrap {
    width: 50%;
    padding: 20px 20px 35px;
    position: relative;
    display: flex;
    flex-direction: column;

    > .info {
      width: 100%;

      > .img-wrap {
        width: 100%;

        > img {
          width: 100%;
        }
      }
    }

    > .price-wrap {
      position: relative;
      margin-top: auto;
      width: 100%;

      > .line {
        color: #3a3a3a;
        font-size: 20px;
        font-style: italic;
        line-height: 1.8;
        margin-bottom: 4px;
      }
    }

  }
}

.pay-btn {
  position: absolute;
  bottom: 0;
  right: 0;
  color: #fff;
  background: #f56c6c;
  transition: all 0.4s ease;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 164px;
  height: 54px;
  cursor: pointer;

  &:hover {
    opacity: 0.75;
  }
}

.un-in-range {
  color: #aaa;
}
</style>